package com.ck.common.service.impl;

import com.ck.common.service.DepartmentService;
import com.ck.common.service.OperationLogService;
import com.ck.constant.*;
import com.ck.dao.DepartmentMapper;
import com.ck.model.common.Department;
import com.ck.model.common.OperationLog;
import com.ck.model.common.User;
import com.ck.model.common.dto.DepartmentTreeDTO;
import com.ck.model.common.page.PageInfo;
import com.ck.model.common.vo.DepartmentListVO;
import com.ck.model.common.vo.DepartmentSelectListVO;
import com.ck.util.HttpUtils;
import com.ck.util.TreeUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.rmi.ServerException;
import java.util.ArrayList;
import java.util.List;

/**
 * 部门Service实现类
 *
 * @author dxy
 * @date 2018/6/21 16:42
 */
@Service(value = "departmentService")
public class DepartmentServiceImpl implements DepartmentService {

	@Autowired
	private DepartmentMapper departmentMapper;
	@Autowired
	private OperationLogService operationLogService;

	/**
	 * 保存部门
	 *
	 * @param department Department
	 * @param request    HttpServletRequest
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void insertDepartment(Department department, HttpServletRequest request) {
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		String companyCode = loginUser.getCompanyCode();
		department.setCompanyCode(companyCode);
		department.setAddTime(System.currentTimeMillis());
		departmentMapper.insertDepartment(department);
		//记录操作日志
		OperationLog operationLog = new OperationLog();
		operationLog.setCopmanyCode(companyCode);
		operationLog.setOperationContent("保存部门,部门ID为:" + department.getDepartmentId());
		operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
		operationLog.setOperationTime(System.currentTimeMillis());
		operationLog.setOperationModule(ModuleConstant.MODULE_USER_PERMISSION + "-" + ModuleConstant.MODULE_DEPARTMENT);
		operationLog.setRealname(loginUser.getRealname());
		operationLog.setUserName(loginUser.getUserName());
		operationLog.setOperationIp(HttpUtils.getRemortIP(request));
		operationLogService.saveOperationLog(operationLog);
	}

	/**
	 * 修改部门
	 *
	 * @param department Department
	 * @param request    HttpServletRequest
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void updateDepartment(Department department, HttpServletRequest request) {
		department.setUpdateTime(System.currentTimeMillis());
		departmentMapper.updateDepartment(department);
		//记录操作日志
		User loginUser = (User) request.getSession().getAttribute(RequestConstant.SESSION_KEY_USER);
		String companyCode = loginUser.getCompanyCode();
		OperationLog operationLog = new OperationLog();
		operationLog.setCopmanyCode(companyCode);
		operationLog.setOperationContent("修改部门,部门ID为:" + department.getDepartmentId());
		operationLog.setOperationStatus(BusinessConstant.OPERATION_LONG_OPERATION_STATUS_SUCCESS);
		operationLog.setOperationTime(System.currentTimeMillis());
		operationLog.setOperationModule(ModuleConstant.MODULE_USER_PERMISSION + "-" + ModuleConstant.MODULE_DEPARTMENT);
		operationLog.setRealname(loginUser.getRealname());
		operationLog.setUserName(loginUser.getUserName());
		operationLog.setOperationIp(HttpUtils.getRemortIP(request));
		operationLogService.saveOperationLog(operationLog);
	}

	/**
	 * 通过部门ID获取部门
	 *
	 * @param departmentId 部门ID
	 * @return Department
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public Department getDepartmentById(Long departmentId) {
		return departmentMapper.getDepartmentById(departmentId);
	}

	/**
	 * 部门列表
	 *
	 * @param status         状态
	 * @param departmentName 部门名称
	 * @param companyCode    公司编号
	 * @return Page<DepartmentListVO>
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public PageInfo<DepartmentListVO> listDepartment(Integer status, String departmentName, String companyCode, Integer pageNum, Integer pageSize) throws ServerException {
		if (StringUtils.isBlank(companyCode)) {
			throw new ServerException("公司编码不能为空");
		}
		//设置默认值
		if (pageNum == null) {
			pageNum = PageConstant.DEFAULT_PAGE_NUM;
		}
		if (pageSize == null) {
			pageSize = PageConstant.DEFAULT_PAGE_SIZE;
		}
		PageHelper.startPage(pageNum, pageSize);
		Page<DepartmentListVO> page = departmentMapper.listDepartment(status, departmentName, companyCode);
		//把Page转化为PageInfo
		PageInfo<DepartmentListVO> pageInfo = new PageInfo<>();
		pageInfo.setPageNum(pageNum);
		pageInfo.setPageSize(pageSize);
		pageInfo.setTotal(page.getTotal());
		pageInfo.setList(page.getResult());
		return pageInfo;
	}

	/**
	 * 获取所有启用的部门
	 *
	 * @return List<DepartmentSelectListVO>
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public List<DepartmentSelectListVO> listDepartmentSelect(String companyCode) throws ServerException {
		if (StringUtils.isBlank(companyCode)) {
			throw new ServerException("公司编码不能为空");
		}
		return departmentMapper.listDepartmentSelect(companyCode, BusinessConstant.STATUS_ENABLE);
	}

	/**
	 * 获取部门树列表
	 *
	 * @param companyCode 商家编码
	 * @return List<DepartmentTreeDTO>
	 * @throws ServerException
	 */
	@Override
	public List<DepartmentTreeDTO> listDepartmentTree(String companyCode) throws ServerException {
		if (StringUtils.isBlank(companyCode)) {
			throw new ServerException("输入参数不能为空");
		}
		List<DepartmentTreeDTO> departmentTreeList = departmentMapper.listDepartmentTree(companyCode, BusinessConstant.STATUS_ENABLE);
		if (CollectionUtils.isNotEmpty(departmentTreeList)) {
			return TreeUtils.getTreeList(departmentTreeList);
		}
		return new ArrayList<>();
	}

	/**
	 * 禁用启用部门
	 *
	 * @param department 待操作的部门
	 * @param user       登录的用户
	 * @param ip         登录用户的ip
	 * @author linqiang
	 */
	@Override
	public void enableDisableDepartment(Department department, User user, String ip) {
		String msg = "%s，部门ID为:%s";
		if (OperationType.DISABLE_DEPARTMENT.getValue().equals(department.getStatus())) {
			//禁用
			msg = String.format(msg, OperationType.DISABLE_DEPARTMENT.getName(), department.getDepartmentId());
		} else if (OperationType.ENABLE_DEPARTMENT.getValue().equals(department.getStatus())) {
			//启用
			msg = String.format(msg, OperationType.ENABLE_DEPARTMENT.getName(), department.getDepartmentId());
		}
		department.setUpdateTime(System.currentTimeMillis());
		departmentMapper.updateDepartment(department);
		operationLogService.saveSuccessOperationLog(msg,
				(ModuleConstant.MODULE_USER_PERMISSION + "-" + ModuleConstant.MODULE_DEPARTMENT), user, ip);
	}
}
